#define _CRT_SECURE_NO_WARNINGS 1

//https://leetcode.cn/problems/generate-parentheses/

class Solution {
    string path;
    vector<string> ret;
    int left = 0, right = 0;
public:
    vector<string> generateParenthesis(int n) {
        dfs(n);
        return ret;
    }

    void dfs(int n)
    {
        if (path.size() == 2 * n)
        {
            ret.push_back(path);
            return;
        }

        if (left < n)
        {
            path.push_back('(');
            left++;
            dfs(n);
            path.pop_back();
            left--;
        }

        if (left > right)
        {
            path.push_back(')');
            right++;
            dfs(n);
            path.pop_back();
            right--;
        }
    }
};